# -- coding: utf-8 --
"""
# [Example] Miahx© 交互框架信息表示模型的 DDS 消息收发示例

**模块：MIAHX© / 框架基础服务层（FFST） / 交互框架信息表示模型（IFIRM）**

Version: 0.4.10,
Last updated: October 11, 2024

## Contributor(s)
* YAO Naiming <[naiming@iscas.ac.cn](mailto:naiming@iscas.ac.cn)>

## Change log
### v0.4.10
- .13: [更新] 适配新消息定义
- .11: [更新] 适配新消息定义 (deprecated)
- .2: [更新] 适配新接口
### v0.4.7
- .24：[新增] 初始实现

---
Copyright © 2024-2025 MIAHX Contributors, ISCAS, and ASIC. All Rights Reserved.
Licensed under Apache-2.0.
"""

import threading
import time

import numpy as np
from miahx_support.dds.fastdds import *
from miahx_support.stag import STag

import launcher


def physio_writer(p: Participant, e: threading.Event):
    stag = STag(**dict(sensor_channel=1, sensor_domain='HUMAN', sensor_type='PEEG_NEURACLE',
                       sensor_channel_type='BRAIN', sensor_modality='PHYSIO', sensor_data_format='CSV')).encode()
    writer = PhysioStreamWriter(p, topic, stag=stag, srate=1000, schns=['EMG_0', 'EMG_1'])
    while not e.is_set():
        rawdata = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float64)
        items = [(1, 1.0, rawdata),
                 (2, 2.0, rawdata)]
        dtype = EPhysioDataType.PHYSIOLAB.value
        writer.write(items, dtype, iid=0, uts=0)
        time.sleep(1)


def physio_reader(p: Participant, e: threading.Event):
    def on_data_available(data):
        hdr = data.header()
        dm = hdr.header().domain()
        src = hdr.header().source()
        prefix = f'[{dm}::{src}::{name}]'

        schns = tuple(hdr.schns())
        samples = list(data.samples())
        log.info(f'{prefix} stag = `{hdr.stag()}`')
        log.info(f'{prefix} srate = `{hdr.srate()}`')
        log.info(f'{prefix} schns = `{schns}`')
        log.info(f'{prefix} elements = [{len(samples)}]')

        for i, sample in enumerate(samples):
            log.info(f'{prefix} Element [{i}]:')
            log.info(f'{prefix} \t\tdtype = `{sample.dtype()}`')
            print(np.asarray(sample.rawdata()).shape)
            sdata = np.asarray(sample.rawdata()).reshape((-1, len(schns)))
            log.info(f'{prefix} \t\tshape = `{sdata.shape}`')
            log.info(f'{prefix} \t\tfirst = `{sdata[0].tolist()}`')
            log.info(f'{prefix} \t\tlast = `{sdata[-1].tolist()}`')
            log.info(f'{prefix} End Element [{i}] --------')

        log.info(f'{prefix} ----------------')

        # with io.BytesIO() as bio:
        #     np.savetxt(bio, raw_data, fmt='%.06f')
        #     content = bio.getvalue()
        # with open(filename, 'ab') as fp:
        #     # 追加写入
        #     fp.write(content)

    # dt = datetime.datetime.now()
    # uts_ms = int(dt.timestamp() * 1000)  # local timestamp in millisecond
    # # e.g. M001__210702030100001__1716544394441__000000__20240524175314441__RTAG
    # fmt = '{uts}__{y}{m:0>2d}{d:0>2d}{hh:0>2d}{mm:0>2d}{ss:0>2d}.txt'
    # filename = fmt.format(uts=uts_ms, y=dt.year, m=dt.month, d=dt.day,
    #                       hh=dt.hour, mm=dt.minute, ss=dt.second, )

    with PhysioStreamReader(p, topic, on_data_listeners=[on_data_available]) as reader:
        name = type(reader).__name__
        log.success(f'[{name}] Topic: {reader.topic_name}')
        reader.wait(e)


if __name__ == '__main__':
    log = launcher.log
    event = threading.Event()
    participant = Participant()
    topic = Topics.DEV_PHYSIOLAB

    launcher.run(lambda: (event, [
        threading.Thread(target=physio_writer, args=(participant, event), daemon=False),
        threading.Thread(target=physio_reader, args=(participant, event), daemon=False),
    ]))
